//
//  OYCNetManager.swift
//  WeiBo-Swift
//
//  Created by daniel on 2017/8/5.
//  Copyright © 2017年 daniel. All rights reserved.
//

import UIKit
import AFNetworking

enum OYCRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class OYCNetManager: AFHTTPSessionManager {
    
    fileprivate let AppKey = "3402115420"
    fileprivate let AppSecret = "b07ea92b6a26ef21c850dbfde6b85854"
    fileprivate let redirectUri = "https://www.baidu.com"
    
    static let sharedTools: OYCNetManager = {
        let tools = OYCNetManager(baseURL: nil)
//        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        return tools
    }()
    
    /// 返回 token 字典
    fileprivate var tokenDict: [String: AnyObject]? {
        // 判断 token 是否有效
        if let token = OYCUserViewModel.shared.accessToken {
            
            return ["access_token": token as AnyObject]
        }
        
        return nil
    }

    
}

// MARK: - OAuth 相关方法
extension OYCNetManager {
    
    /// OAuth 授权地址
    /// - see: [http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
    var oauthUrl: URL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(redirectUri)"
        return URL(string: urlString)!
    }
    
    /// 加载 Token
    /// - parameter code: 授权码
    /// - see: [http://open.weibo.com/wiki/OAuth2/access_token](http://open.weibo.com/wiki/OAuth2/access_token)
    func loadAccessToken(code: String, finished: @escaping RequestCallBack) {
        
        let url = "https://api.weibo.com/oauth2/access_token"
        let param = ["client_id" : AppKey,
                     "client_secret" : AppSecret,
                     "grant_type" : "authorization_code",
                     "code" : code,
                     "redirect_uri" : redirectUri]
        
        request(method: OYCRequestMethod.POST, usrlString: url, parameters: param, finished: finished)
    }
    
    /// 加载用户信息
    ///
    /// - parameter uid:         uid
    /// - parameter finished:    完成回调
    /// - see: [http://open.weibo.com/wiki/2/users/show](http://open.weibo.com/wiki/2/users/show)
    func loadUserInfo(uid: String, finished: @escaping RequestCallBack) {
        
        // 1. 获取 token 字典
//        guard var params = tokenDict else {
//            
//            // 如果字典为 nil，通知调用方，token 无效
//            finished(nil, NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
//            
//            return
//        }
        // 2. 处理网络参数
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let params = [ "access_token" : OYCUserViewModel.shared.accessToken,
                       "uid" : uid]
        
        request(method: .GET, usrlString: urlString, parameters: params, finished: finished)
    }

}

extension OYCNetManager {
    
    typealias RequestCallBack = (_ result: Any?, _ error: Error?) -> Void
    
    func request(method: OYCRequestMethod, usrlString: String, parameters: Any?, finished: @escaping RequestCallBack) {
        
        let successBlock = { (_ task: URLSessionDataTask, _ result: Any) -> Void in
            finished(result, nil)
        }
        
        let failureBlock = { (_ task: URLSessionDataTask?, _ error: Error) -> Void in
            finished(nil, error)
        }
        
        if method == OYCRequestMethod.GET {
           get(usrlString, parameters: parameters, progress: nil, success: successBlock, failure: failureBlock)
        }else {
            post(usrlString, parameters: parameters, progress: nil, success: successBlock, failure: failureBlock)
        }

    }
    
}
